#!/bin/bash

cd $(dirname $0)
BASE=$(pwd)

VERSION=$(grep "public static final String VERSION" "${BASE}/src/fsahoraires/Main.java" | sed 's/.*VERSION = "\(.*\)";/\1/')

BINDIR="bin"
METADIR="META-INF"
OUTPUT="fsa-horaires-${VERSION}.jar"
TEMPDIR="temp"

KEYSTORE="keystore"
KEYSTORE_ALIAS="fsa-horaires"

# foncion recursive pour "${BINDIR}/"
function recurse_bin()
{
	echo "     >> entering ${BINDIR}/$1"
	for f in $1*; do
		if [ -d $f ]; then
			if [ ${f:${#f}-4:4} != 'test' ]; then
				if [ ! -e "${BASE}/${TEMPDIR}/$f" ]; then
					mkdir "${BASE}/${TEMPDIR}/$f"
				fi
				recurse_bin "$f/"
			else
				echo "         - ommiting $f"
			fi
		else
			echo "         + copying $f"
			cp $f "${BASE}/${TEMPDIR}/$1"
		fi
	done
	echo "     >> leaving ${BINDIR}/$1"
}

function recurse_meta()
{
	echo "     >> entering ${METADIR}/$1"
	for f in $1*; do
		if [ -d $f ]; then
			if [ ! -e "${BASE}/${TEMPDIR}/META-INF/$f" ]; then
				mkdir "${BASE}/${TEMPDIR}/META-INF/$f"
			fi
			recurse_meta "$f/"
		else
			echo "         + copying META-INF/$f"
			cp $f "${BASE}/${TEMPDIR}/META-INF/$1"
		fi
	done
	echo "     >> leaving META-INF/$1"
}

function die() {
	if [ -n $1 ]; then
		echo $1
	fi
	exit 1
}

# repertoire temporaire
echo ">>> creating temp dir"
mkdir "${BASE}/${TEMPDIR}" || die

echo ">>> copying classes"
cd "${BASE}/${BINDIR}" || die
recurse_bin

echo ">>> copying manifest"
mkdir "${BASE}/${TEMPDIR}/META-INF" || die
cd "${BASE}/${METADIR}" || die
recurse_meta

echo ">>> creating jar"
cd "${BASE}/${TEMPDIR}" || die
if [ -e "${BASE}/${OUTPUT}" ]; then
	rm "${BASE}/${OUTPUT}" || die
fi
jar -cMf "${BASE}/${OUTPUT}" * || die

echo ">>> removing temp dir"
cd "${BASE}" || die
rm -r ${TEMPDIR}

echo ">>> signing jar"
jarsigner -keystore "${BASE}/${KEYSTORE}" "${BASE}/${OUTPUT}" $KEYSTORE_ALIAS

